<html>
<head>
    <script src="../../resources/js-test.js"></script>
    <script src="../../resources/testharness.js"></script>
    <script src="../../resources/visibility.js"></script>
    <script>
        description('<a href="http://crbug.com/259680">Bug 259680</a>: JavaScript setInterval lagging behind');

        var jsTestIsAsync = true;
        var intervalDuration = 1000;
        var testDuration = 4000;
        var expectedNumFires = 4;
        var numFires = 0;
        var tolerance = 1;

        var intervalID;
        var startTime;

        function timerFired()
        {
            ++numFires;

            var currentTime = new Date().getTime();
            if (currentTime >= startTime + testDuration) {
                shouldBeCloseTo("numFires", expectedNumFires, tolerance);

                clearInterval(intervalID);
                finishJSTest();
                return;
            }
        }

        function runTest()
        {
            assert_equals(document.visibilityState, "hidden");

            if (!window.testRunner) {
                debug('This test requires testRunner');
                return;
            }

            startTime = new Date().getTime();
            intervalID = window.setInterval(timerFired, intervalDuration);
        }
    </script>
</head>
<body onload="setMainWindowHidden(true).then(runTest)">
    <p>
    This test ensures that intervals on background pages whose duration is close to the timer alignment interval don't miss every other firing.
    </p>
</body>
</html>
